<?php

class UsersController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	public $defaultAction='View';
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','connect'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{	
		$model=new users;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['users']))
		{
			$model->attributes=$_POST['users'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->user_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['users']))
		{
			$model->attributes=$_POST['users'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->user_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel()->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		
		$model=new users();
		$model->user_id=23;
		$model->login_name='qq497688075';
		$model->email='497688075@qq.com';
		$model->password='abc4666883';
		//$model->save();
		$model=new users();
		$model=users::model()->find("user_id",array(23));
		//print_r($model);
		$dataProvider=new CActiveDataProvider('users');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new users('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['users']))
			$model->attributes=$_GET['users'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=users::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionConnect(){
	    //get provider
	    $provider = '';
	    if(!empty($_GET['provider'])){
	        $provider = $_GET['provider'];
	    }
	    //判断是什么网站，对应不同配置
	    $accessSite = 'platform';
	    if(!empty($_GET['site'])){
	        $accessSite = $_GET['site'];
	    }
	    
	    $redirect = isset($_REQUEST['redirect']) ? $_REQUEST['redirect'] : '/';
    	if(!empty($_SESSION['user_id']))
    	{
    		$this->redirect(array(
    		    'site/index'
    		));exit;
    	}
	    try
	    {
	        //判断provider，并加载对应的类
    	    if($provider == NULL)throw new CHttpException(404,'No Provider.');
    	    $configOption = Yii::app()->params["third_login_{$provider}"][$accessSite];
    	    $configOption['redirect_uri'] = Yii::app()->request->hostInfo.$configOption['redirect_uri'];
    	    $classname = 'T'.$provider;
    	    if(!class_exists($classname))throw new CHttpException(404,'Error Provider Class.');
    	    $connector = new $classname($configOption);
    	    //开始连接
    	    if (! $connector->is_callback_url())
    		{
    			$url = $connector->get_login_url($redirect);
    			header('location: ' . $url);
    			exit();
    		}
    		
    		//获取信息
    	    if (! empty($_REQUEST['email']))
    		{
    			$connect_user['email'] = $_REQUEST['email'];
    		}
    		else
    		{
    			$connect_user = $connector->get_user();
    		}
    		
    		if(empty($connect_user['email']))throw new CHttpException(404,'The email error.');
    		
    		$userInfo = Users::model()->findByAttributes(array('email'=>$connect_user['email']));
    		
    		//判断用户，并做注册或登录操作
    		if ($userInfo->user_id >0)
    		{
    		    //login 操作
    		    //TODO:后续更改为model的login操作
    		    Yii::app()->session['username']=$userInfo->login_name;
				Yii::app()->session['password']=$userInfo->password;
				Yii::app()->session['email']=$userInfo->email;
				Yii::app()->session['user_id']=$userInfo->user_id;
    		}else{
    		    //注册操作
    		    echo 'no user';
    		}
	    }catch(ErrorException $err){
//	        echo $err['message'];
//    	    if ($error = Yii::app ()->errorHandler->error) {
//    			if (Yii::app ()->request->isAjaxRequest)
//    				echo $error ['message'];
//    			else
//    				$this->render ( 'error', $error );
//    		}
//	        print_r($err);
	    }
	    exit;
	}
}

